package com.yourname.projectname.service.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yourname.projectname.dto.user.UserLoginDTO;
import com.yourname.projectname.dto.user.UserRegisterDTO;
import com.yourname.projectname.entity.user.User;
import com.yourname.projectname.mapper.user.UserMapper;
import com.yourname.projectname.result.Result;
import com.yourname.projectname.service.user.UserAuthService;
import com.yourname.projectname.util.JwtUtil;
import com.yourname.projectname.util.PwdUtil;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 用户登录服务实现类
 */
@Service
public class UserAuthServiceImpl implements UserAuthService {

    @Resource
    private UserMapper userMapper;

    /**
     * 用户登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public Result login(UserLoginDTO userLoginDTO) {
        // 获取用户名和将明文密码加密
        String account= userLoginDTO.getAccount();
        String password = PwdUtil.PwdWithSalt(userLoginDTO.getPassword());

        // 查询用户
        User user = userMapper.selectOne(
                new QueryWrapper<User>()
                        .eq("account", account)
                        .eq("password", password)
        );

        String role = user.getRole();

        // 若用户为空，则返回错误
        if (user != null) {
            String token = JwtUtil.generateToken(account, role);
            return Result.success(token);
        }
        return Result.unauthorized("用户名或密码错误");
    }

    @Override
    public Result logout() {
        // 实际项目中，可能需要将token加入黑名单

        return Result.success("登出成功");
    }

    /**
     * 用户注册
     * @param userRegisterDTO
     * @return
     */
    @Override
    public Result register(UserRegisterDTO userRegisterDTO) {

        String account = userRegisterDTO.getAccount();
        String phone = userRegisterDTO.getPhone();
        String password = PwdUtil.PwdWithSalt(userRegisterDTO.getPassword());


        User accountUser = userMapper.selectOne(
                new QueryWrapper<User>()
                        .eq("account", account)
        );
        if (accountUser != null) {
            return Result.error("账号已存在,请另取账号");
        }
        User phoneUser = userMapper.selectOne(
                new QueryWrapper<User>()
                        .eq("phone", phone)
        );
        if (phoneUser != null) {
            return Result.error("手机号已存在,请检查手机号是否正确");
        }


        User user = new User();
        user.setAccount(account);
        user.setPhone(phone);
        user.setPassword(password);
        if(userMapper.insert(user) == 1) {
            return Result.success( "注册成功");
        }
        return Result.error("注册失败");
    }
}
